/*
 * This class will be called from the variable menu when user select particular month from the month dialog.
 */
package com.fipl.parse;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

public class SelectVariableParser {
	
	private static final String url1 = "http://megan.teksar.com.mx/jsonaverage.php?dbname=";
	private static final String url2 = "&action=select&table=average&month=";
	private URL url;
	private HttpURLConnection httpURLConnection=null;
	private InputStream inputStream;
	private StringBuffer jsonText = null;
	public SelectVariableParse selectVariableParse;
	
	public SelectVariableParser(String dbName,String month, String year,String variable){
		try{
			selectVariableParse = new SelectVariableParse();
			url = new URL(url1+dbName+url2+month+"&year="+year+"&field="+variable);
			httpURLConnection = (HttpURLConnection)url.openConnection();
			inputStream = httpURLConnection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
			String lineBuffer = null ;
			jsonText = new StringBuffer();
			do{
				lineBuffer = br.readLine();
				jsonText.append(lineBuffer);
			}while(lineBuffer!=null);
			httpURLConnection.disconnect();
			br.close();
		}catch (Exception e){
			// TODO: handle exception
			Log.d("System out", "Error "+e.getMessage());
		}
	}

	public int SelectVariableData(){

		int parsedReturn = 0;
		JSONArray jsonArray;
		try{
			jsonArray = new JSONArray(jsonText.toString());
			for(int i=0; i<jsonArray.length();i++){
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				selectVariableParse.fecha.add(jsonObject.getString("fecha"));
				selectVariableParse.record.add(jsonObject.getString("record"));
				selectVariableParse.average.add(jsonObject.getString("average"));
			}
		}catch (Exception e) {
			// TODO: handle exception
			Log.d("System out", "Error "+e.getMessage());
			parsedReturn = -1;
		}
		return parsedReturn;
	}
	
}
